package al56merge;

import java.util.ArrayList;
import java.util.Arrays;

public class Merge {

    public static int[][] merge(int[][] intervals) {
        if ( intervals == null || intervals.length == 0){
            return new int[0][0];
        }
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int[][] result = new int[intervals.length][2];
        result[0] = intervals[0];
        int j = 1;
        int index = 0;
        for( int i= 0;i<intervals.length;i++){
            while (j != intervals.length && result[i][1] >= intervals[j][0]) {
                if(result[i][1] <= intervals[j][1]){
                    result[i][1] = intervals[j][1];
                }
                j++;
            }
            if(j == intervals.length){
                break;
            }
            result[i+1] = intervals[j];
            index++;
        }
        return Arrays.copyOfRange(result, 0, index+1);
    }

    public static void main(String[] args) {
//        int[][] intervals = {{1,4},{0,4}};
        int[][] intervals = {{1,4},{2,3}};
        int[][] merge = merge(intervals);
        for (int i = 0; i < merge.length; i++) {
            System.out.println(Arrays.toString(merge[i]));  // 打印每一行
        }
    }
}
